// pages/scanPay/scanPay.js
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
const pay = require('../../services/pay.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    price:'',
    point:0,
    storeId:'',
    storeDetails: {}, //storeName
    showSuccess:false,
    time:''
  },

  getPrice(event){
    if(event.detail){
      this.setData({
        price: event.detail,
        point: parseInt(event.detail)
      })
    }else{
      this.setData({
        price: '',
        point: 0
      })
    }
  },

  //节流函数，一秒钟内多次点击只触发一次
  pay:util.throttle(function(e){
    this.submitOder()
  },1000),

  submitOder(){
    // 提交订单
    let data = { storeId: this.data.storeId, totalPrice: this.data.price, order_type: 3 }
    if (this.data.price < 0.01) {
      util.showErrorToast('不能少于0.01')
      return
    } else if (isNaN(this.data.price)) {
      util.showErrorToast('请输入正确金额')
      return
    } else {
      util.post(api.submitOrder, data).then(res => {
        wx.showLoading({
          title: '正在提交订单，请稍后...',
        })
        if (res.errno == 0) {
          wx.hideLoading()
          this.payMoney(res.data.orderInfo.id)
        } else {
          wx.hideLoading()
          util.alert(res.errmsg)
        }
      }).catch(err => {
        util.alert(err.msg)
      })
    }
  },

  payMoney(orderId) {
    pay.payOrder(parseInt(orderId)).then(res => {
      if (res.errMsg === 'requestPayment:ok'){
        util.showSuccessToast('支付成功')
        let date = new Date()
        this.setData({ time: util.formatTime(date)})
        setTimeout(()=>{
          this.setData({
            showSuccess:true
          })
        })
      }
    }).catch(res => {
      util.alert(res.msg)
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    util.getUrl()
    if (options.q !== undefined) {
      var scan_url = decodeURIComponent(options.q);
      console.log(scan_url);
      this.setData({
        storeId: scan_url.substring(50)
      })

      util.request(api.storeDetails + scan_url.substring(50)).then((res) => {
        console.log(res)
        if (res.errno == 0) {
          this.setData({ storeDetails: res.data })
        } else {
          util.showErrorToast(res.msg)
        }
      })
    } else {
      console.log('不是扫码进入');
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})